package com.zb.api.business.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.zb.api.common.conts.Const;
import com.zb.api.common.models.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.xml.ws.soap.Addressing;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("captcha")
@CrossOrigin("*")
public class AuthController {

    @Autowired
    private Producer producer;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 获取登录验证码
     * @return
     * @throws IOException
     */
    @GetMapping("getCodeImg")
    public ServerResponse getCaptcha() throws IOException {
        String code = producer.createText();
        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        //redisUtil.hset(Const.captcha_KEY, key, code, 120);
        redisTemplate.opsForValue().set(Const.CAPTCHA_KEY_LOGIN + key,code);
        // 5分钟
        redisTemplate.expire(Const.CAPTCHA_KEY_LOGIN + key,5, TimeUnit.MINUTES);
        log.info("验证码 -- {} - {}", key, code);
        return ServerResponse.success("",MapUtil.builder().
                put("captchaKey", key).
                put("codeImg", base64Img).
                map());
    }

}
